package com.nervenets.web.redis;

import com.google.gson.Gson;
import com.nervenets.utils.StringUtils;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisCommands;

import javax.annotation.Resource;

/**
 * Created by Joe on 2017/12/16.
 */
@Component
public class RedisDao {
    private static final String EXECUTE_RESULT_OK = "OK";
    @Resource
    JedisCommands jedisCluster;

    private static String toJson(RedisDomain domain) {
        return new Gson().toJson(domain);
    }

    public boolean addString(String key, String value, int expire) {
        boolean rtnValue = EXECUTE_RESULT_OK.equals(jedisCluster.set(key, value).toUpperCase());
        if (expire > 0) {
            jedisCluster.expire(key, expire);
        }
        return rtnValue;
    }

    public boolean addString(String key, String value) {
        return EXECUTE_RESULT_OK.equals(jedisCluster.set(key, value).toUpperCase());
    }

    public boolean exist(String key) {
        return jedisCluster.exists(key);
    }

    public void delete(String key) {
        jedisCluster.del(key);
    }

    public String getString(String key) {
        return jedisCluster.get(key);
    }

    public long getExpired(String key) {
        return jedisCluster.ttl(key);
    }

    public void delete(RedisDomain domain) {
        delete(domain.getRedisKey());
    }

    public boolean saveOrUpdate(RedisDomain domain) {
        return saveOrUpdate(domain, domain.getExpire());
    }

    public boolean saveOrUpdate(RedisDomain domain, int expire) {
        return addString(domain.getRedisKey(), toJson(domain), expire);
    }

    public <T extends RedisDomain> T getRedisDomain(String key, Class<? extends T> domainClass) {
        String jsonString = getString(key);
        if (!StringUtils.isEmpty(jsonString)) {
            return new Gson().fromJson(jsonString, domainClass);
        }
        return null;
    }

    public void incrBy(String key, int offset) {
        jedisCluster.incrBy(key, offset);
    }

    public void incr(String key) {
        jedisCluster.incr(key);
    }

    public JedisCommands getCluster() {
        return jedisCluster;
    }
}
